package com.netty;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.logging.Logger;

public class NioDemo2 {

  @Test
  public void test1() throws IOException {

    // 方法一：
    FileInputStream fileInputStream = new FileInputStream("data.txt"); // 读的通道
    FileChannel from = fileInputStream.getChannel();

    FileOutputStream fileInputStream1 = new FileOutputStream("to.txt"); // 写的通道
    FileChannel to = fileInputStream1.getChannel();

    long l = from.transferTo(0, from.size(), to);

    System.out.println(l);

    // 方法二：
    RandomAccessFile r1 = new RandomAccessFile("data.txt", "rw"); // 都开启rw权限
    FileChannel from1 = r1.getChannel();

    RandomAccessFile r2 = new RandomAccessFile("to.txt", "rw");
    FileChannel to2 = r2.getChannel();

    from1.transferTo(0, r1.length(), to2);
  }

  @Test
  public void test2() {

    Path path = Paths.get("data.txt");
    boolean exists = Files.exists(path);

    System.out.println(exists);
  }

  @Test
  public void test3() throws IOException {

    Path path = Paths.get("D:\\img\\a\\b");
    Path directory = Files.createDirectory(path);

    System.out.println(directory);
  }

  @Test
  public void test4() throws IOException {

    Path path = Paths.get("D:\\img\\a\\b");
    Path directories = Files.createDirectories(path);

  }

  @Test
  public void test5() throws IOException {

//    Path from = Paths.get("data.txt");
//    Path path = Paths.get("D:\\img\\target.txt"); //文件名也要写
//    Files.copy(from,path);

//    Path from = Paths.get("data.txt");
//    Path path = Paths.get("D:\\img\\target.txt"); //文件名也要写
//    Files.copy(from,path, StandardCopyOption.REPLACE_EXISTING);

    Path source = Paths.get("data.txt");
    Path target = Paths.get("D:\\img\\target.txt");

    Files.move(source, target, StandardCopyOption.ATOMIC_MOVE);
  }

  @Test
  public void test6() throws IOException {

    Path target = Paths.get("D:\\img\\target.txt");

    Files.delete(target); //删除文件

  }


  @Test
  public void test7() throws IOException {

    Path target = Paths.get("D:\\cTest");

    Files.walkFileTree(target,new SimpleFileVisitor<Path>(){

      @Override
      public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
        System.out.println("1:"+dir);
        return super.preVisitDirectory(dir, attrs);
      }

      @Override
      public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
        System.out.println("2:"+file);
        return super.visitFile(file, attrs);
      }
    });
  }

}
